package middleware.kafka.Serializer;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.utils.Utils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author suxiaoxiao
 * @Date 2019/6/26 23:18
 * @Version 1.0
 */
public class DemoPartitioner implements Partitioner {

    /**
     * 原子操作 CAS原理 实现无锁线程安全
     */
    private final AtomicInteger counter = new AtomicInteger(0);

    /**
     *
     * @param topic 主题
     * @param key 键
     * @param keyBytes 序列化后的键
     * @param value 序列化后的值
     * @param valueBytes 序列化后的值
     * @param cluster 集群的元数据
     * @return
     */
    @Override
    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topic);
        int numPartitions = partitionInfos.size();
        if (null == keyBytes) {
            // getAndIncrement() 获取当前值 并自增
            return counter.getAndIncrement() % numPartitions;
        } else {
            return Utils.toPositive(Utils.murmur2(keyBytes)) % numPartitions;
        }
    }

    @Override
    public void close() {

    }

    @Override
    public void configure(Map<String, ?> map) {

    }
}
